(function (vc) {

    vc.extends({
        data: {
            searchCommunityDataInfo: {
                searchValue: '',
                rooms: [],
                owners: [],
                ownerMembers: [],
                cars: [],
                carMembers: [],
                contracts: [],
                repairs: [],
                visits: [],
                staffs: [],
                noData: true,
                machine: {},
                ws: {},
                componentName:''
            },
        },
        _initMethod: function () {
            $that._initTelMachine();
        },
        _initEvent: function () {
            vc.on('searchCommunityDataModel', '_loadData', function (_param) {
                $that._clearSearchCommunityData();
                //$('#searchCommunityDataModel').modal('show');
            });
            vc.on('searchCommunityDataModel', 'playTts', function (_data) {
                $that.searchCommunityDataInfo.ws.send(
                    JSON.stringify({
                        action: 'PlayMusic',
                        url: _data.url,
                        file_name:vc.uuid()+'.wav',
                        volume:100,
                        loop:true
                    })
                );

            });
            vc.on('searchCommunityDataModel', 'hangup', function () {
                $that.searchCommunityDataInfo.ws.send(
                    JSON.stringify({
                        action: 'Hangup'
                    })
                );
            });
            vc.on('searchCommunityDataModel', 'callTel', function (_data) {
                $that.searchCommunityDataInfo.ws.send(
                    JSON.stringify({
                        action: 'CallOut',
                        number: _data.tel,
                        cb:'callout_cb'
                    })
                );
                $that.searchCommunityDataInfo.componentName = _data.componentName;

            });
            vc.on('searchCommunityDataModel', 'sendTelMsg', function (_data) {
                $that.searchCommunityDataInfo.ws.send(
                    JSON.stringify({
                        action: 'SmsSend',
                        number: _data.tel,
                        content: _data.msgText
                    })
                );
            });
        },
        methods: {
            _doSearchCommunityData: function () {
                if (!vc.isNotEmpty($that.searchCommunityDataInfo.searchValue)) {
                    vc.toast('请输入查询条件');
                    return;
                }
                // 清理信息
                let _param = {
                    params: {
                        searchValue: $that.searchCommunityDataInfo.searchValue,
                        communityId: vc.getCurrentCommunity().communityId
                    }
                }
                vc.http.apiGet('/search.searchCommunityData',
                    _param,
                    function (json, res) {
                        let _ownerJson = JSON.parse(json);
                        if (_ownerJson.code != 0) {
                            vc.toast(_ownerJson.msg);
                            return;
                        }
                        $that.searchCommunityDataInfo.noData = false;
                        _ownerJson = _ownerJson.data;
                        $that.searchCommunityDataInfo.rooms = _ownerJson.rooms;
                        $that.searchCommunityDataInfo.owners = _ownerJson.owners;
                        $that.searchCommunityDataInfo.ownerMembers = _ownerJson.ownerMembers;
                        $that.searchCommunityDataInfo.cars = _ownerJson.cars;
                        $that.searchCommunityDataInfo.carMembers = _ownerJson.carMembers;
                        $that.searchCommunityDataInfo.contracts = _ownerJson.contracts;
                        $that.searchCommunityDataInfo.repairs = _ownerJson.repairs;
                        $that.searchCommunityDataInfo.visits = _ownerJson.visitDtos;
                        $that.searchCommunityDataInfo.staffs = _ownerJson.staffs;
                        if (_ownerJson.rooms.length < 1 && _ownerJson.owners.length < 1 && _ownerJson.ownerMembers.length < 1
                            && _ownerJson.cars.length < 1 && _ownerJson.carMembers.length < 1 && _ownerJson.contracts.length < 1
                            && _ownerJson.repairs.length < 1 && _ownerJson.visitDtos.length < 1 && _ownerJson.staffs.length < 1
                        ) {
                            $that.searchCommunityDataInfo.noData = true;
                        }
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _toSimplifyAcceptance: function (_room) {
                let _date = new Date();
                vc.saveData("JAVA110_IS_BACK", _date.getTime());
                vc.saveData('simplifyAcceptanceSearch', {
                    searchType: '1',
                    searchValue: _room.floorNum + "-" + _room.unitNum + "-" + _room.roomNum,
                    searchPlaceholder: '请输入房屋编号 楼栋-单元-房屋 如1-1-1',
                })
                window.open('/#/pages/property/simplifyAcceptance?tab=业务受理');
            },
            _clearSearchCommunityData: function () {
                let _ws = $that.searchCommunityDataInfo.ws;
                let _machine = $that.searchCommunityDataInfo.machine;

                $that.searchCommunityDataInfo = {
                    searchValue: '',
                    noData: true,
                    rooms: [],
                    owners: [],
                    ownerMembers: [],
                    cars: [],
                    carMembers: [],
                    contracts: [],
                    repairs: [],
                    visits: [],
                    staffs: [],
                    machine: _machine,
                    ws: _ws
                };
            },
            _initTelMachine: function (_page, _row) {
                let _communityId = vc.getCurrentCommunity().communityId;
                if(!_communityId || _communityId == '-1'){
                    return;
                }
                let param = {
                    params: {
                        page: 1,
                        row: 1,
                        communityId: vc.getCurrentCommunity().communityId,
                        iotApiCode: 'queryTelMachineBmoImpl'
                    }
                };
                vc.http.apiGet('/iot.getOpenApi',
                    param,
                    function (json, res) {
                        let _json = JSON.parse(json);
                        if (_json.code != 0 || _json.data.length < 1) {
                            return;
                        }
                        let _data = _json.data[0];
                        $that.searchCommunityDataInfo.machine = _data;
                        $that._connectTelMachine(_data);

                    }, function () {
                        console.log('请求失败处理');
                    }
                );
            },
            _queryCallInTel: function () {
                let _ws = $that.searchCommunityDataInfo.ws;
                if (!_ws) {
                    vc.toast('未连接固定电话');
                    return;
                }
                $that.searchCommunityDataInfo.ws.send(
                    JSON.stringify({
                        action: 'Query',
                        type: 'Device',
                        cb: 'cb_data'
                    })
                );

            },
            _connectTelMachine: function (_machine) {
                let _protocol = window.location.protocol;
                let url = "ws://";
                if (_protocol.startsWith('https')) {
                    url = "wss://";
                }
                url = url + _machine.machineIp + ":" + _machine.machinePort + "/APP_2AD85C71-BEF8-463C-9B4B-B672F603542A_fast";
                let ws = new WebSocket(url);
                ws.onerror = function (event) {
                    console.log('消息', event.data);
                    setTimeout(function () {
                        $that._connectTelMachine(_machine);
                    }, 2)
                };
                ws.onclose = function (event) {    //断开连接函数  
                };
                //与WebSocket建立连接  
                ws.onopen = function (event) { //连接成功函数  
                };
                ws.onmessage = function (data) {
                    console.log(data.data);
                    data = JSON.parse(data.data);
                    if (data.message == 'query') { //主动查询时的返回
                        if (data.name == 'Device' && data.param.CallerId) {
                            $that._clearSearchCommunityData();
                            $that.searchCommunityDataInfo.searchValue = data.param.CallerId;
                            $that._doSearchCommunityData();
                            return;
                        }
                        if (data.name == 'Device' && data.param.hasOwnProperty('CallerId')) {
                            vc.toast('座机未返回通话中号码');
                            return;
                        }
                        return;
                    }
                    let param = data.param;

                    if (param && param.status == 'CallIn') {
                        $that._clearSearchCommunityData();
                        $that.searchCommunityDataInfo.searchValue = param.number;
                        $('#searchCommunityDataModel').modal('show');
                        $that._doSearchCommunityData();
                        return;
                    }
                    if (param && param.status == 'TalkingStart') {
                        vc.emit($that.searchCommunityDataInfo.componentName,'TalkingStart',param);
                        return;
                    }
                    if (param && param.status == 'TalkingEnd') {
                        vc.emit($that.searchCommunityDataInfo.componentName,'TalkingEnd',param);
                        return;
                    }
                    
                    $that._saveTelMachineMsg(data);

                }
                $that.searchCommunityDataInfo.ws = ws;
            },
            _saveTelMachineMsg: function (_data) {
                _data.iotApiCode = 'telMachineMsgBmoImpl';
                _data.communityId = vc.getCurrentCommunity().communityId;
                _data.machineId = $that.searchCommunityDataInfo.machine.machineId;
                vc.http.apiPost('/iot.postOpenApi',
                    JSON.stringify(_data),
                    {
                        emulateJSON: true
                    },
                    function (json, res) {

                        let _json = JSON.parse(json);
                        if (_json.code != 0) {
                            console.log('同步座机信息失败', _data.msg)
                            return;
                        }
                        console.log(_json, _json.data)

                        let _param = _json.data || {};

                        if (_param.action == 'sms') {

                            vc.emit('searchCommunityDataModel', 'sendTelMsg', {
                                tel: _param.tel,
                                msgText: _param.msgText
                            });

                        }

                    }, function () {
                        console.log('请求失败处理');
                    }
                );
            },
        }
    });

})(window.vc);